#include <iostream>
#include <sstream>
#include <string>
#include <memory>
#include <jsoncpp/json/json.h>

bool Serialize(Json::Value &val, std::string &body)
{
    Json::StreamWriterBuilder swb;
    std::unique_ptr<Json::StreamWriter> sw(swb.newStreamWriter());

    std::stringstream ss;
    int ret = sw->write(val, &ss);
    if (ret != 0)
    {
        std::cout << "json serialize failed" << std::endl;
        return false;
    }
    body = ss.str();
    return true;
}

bool Deserialize(Json::Value &val, std::string &body)
{
    Json::CharReaderBuilder crb;
    std::unique_ptr<Json::CharReader> cr(crb.newCharReader());

    std::string err;
    bool ret = cr->parse(body.c_str(), body.c_str() + body.size(), &val, &err);
    if (ret == false)
    {
        std::cout << "json deserialize failed :" << err << std::endl;
    }

    return ret;
}

int main()
{
    const char *name = "小朱";
    int age = 18;
    const char *sex = "男";
    float score[] = {88.5f, 77.0f, 66.0f};

    Json::Value student;
    student["名字"] = "小朱";
    student["年龄"] = 18;
    student["性别"] = "男";
    for (auto &e : score)
    {
        student["成绩"].append(e);
    }
    Json::Value fav;
    fav["书籍"] = "水浒传";
    fav["运动"] = "乒乓球";
    student["爱好"] = fav;

    std::string body;
    // 序列化
    Serialize(student, body);
    std::cout << body << std::endl;

    Json::Value stu;
    Deserialize(stu, body);
    std::cout << stu["名字"].asCString() << std::endl;
    std::cout << stu["年龄"].asInt() << std::endl;
    std::cout << stu["性别"].asCString() << std::endl;
    int sz = stu["成绩"].size();
    for (int i = 0; i < sz; i++)
        std::cout << "成绩 :" << stu["成绩"][i].asFloat() << std::endl;
    return 0;

}